//
//  OAuthViewController.swift
//  CYMWeiBo-20
//
//  Created by mac on 15/12/15.
//  Copyright © 2015年 IT 小码农. All rights reserved.
//

import UIKit
import SVProgressHUD
//import SDWebImage
import AFNetworking

//授权
class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    //加上 private 表示既可以被识别又不让外界访问
    
    //关闭按钮
    @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //MARK:自动填充
    @objc private func defaultAccount() {
    
        let jsString = "document.getElementById('userId').value = '15101621715' , document.getElementById('passwd').value = 'lilili521'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func loadView() {
    //根视图赋值为 webView
        view = webView
        
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        print(view.classForCoder)
        loadOAuthPage()
        setNavBar()
    }
    //MARK: 加载授权页面
    private func loadOAuthPage() {
    
        //urlString 
//        微博 API 授权url + App Key + 授权页回调
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_url
        
        let url = NSURL(string: urlString)
        
        //一定有值
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    
    //MARK:设置导航条
    private func setNavBar() {
    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
}

//MARK: extension 扩展 授权控制器
extension OAuthViewController:UIWebViewDelegate {

    //协议方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /*
     授权成功后的回调 页面-->微博主页
http://weibo.com/5787031453?code=2480a4dcc98a896b13fd4996032cec1f
    =====================
    希望加载的页面-->登陆页面
    Optional(https://api.weibo.com/oauth2/authorize?client_id=1621079340&redirect_uri=http://weibo.com/5787031453)
    
    Optional("https://api.weibo.com/oauth2/authorize?client_id=1621079340&redirect_uri=http://weibo.com/5787031453")
    请求授权页面
    Optional(https://api.weibo.com/oauth2/authorize)

    
     */
    
    //协议方法 返回值为 bool 返回 true 正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //absolute绝对-->阿布死喽的
//        let urlString = request.URL?.absoluteString
//        print(urlString)

        //根据请求的 url 屏蔽掉不希 望加载的页面 guard守卫
        guard  let urlString = request.URL?.absoluteString else {
        return false
        }
        
        //走到这一步, uerString 一定有值  Prefix前缀
        if urlString.hasPrefix("https://api.weibo.com/") {
        
            //希望加载页面
        return true
        }
        
        
        //此句会把注册按钮给屏蔽,
        if !urlString.hasPrefix("http://weibo.com/5787031453") {
        
            //一定不是请求成功后的回调 ,同样也不是希望加载的页面
            return false
        }
        
        //程序走到这里一定是授权成功的回调-->微博主页
        print(urlString) //http://weibo.com/5787031453?code=6918c63677f85b58b04dab140b7dbcc6
        
        
        //解析字符串获取 code 码
        //query 查询--->获取到 url 中参数部分 键值
        let query = request.URL?.query
//        print(query)//code=6918c63677f85b58b04dab140b7dbcc6
        
        //如果不为空 进行字符串截取
        if let q = query {
        //字符串截取操作
            let codeStr = "code="
            //从 query 中找 code= ,找到后从=后面截取字符串 form上面  from 来自
            let code = q.substringFromIndex(codeStr.endIndex)
        
            
            //加载用户 token象征
            loadAccessToken(code)
        }
        
        return true
    }
    //MARK: 加载用户 token 请求标识 access 入口,进入,访问
    private func loadAccessToken(code:String) {
        
        //实例化视图模型对象 ,调用对象方法
               UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
                if isSuccess {
                print("登陆成功")
                    self.close()
                } else {
                print("登录失败")
                }
        }
    }
    
   
}





